﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace SuperKit {
    public class CountVideo : CommandExecutor {
        // 如果为True，则表示[多少P]的会追加到前面
        public bool IsFront { get; }
        // 如果为True，则表示只删除信息，不增加信息
        public bool IsRemove { get; }
        // 是否显示分辨率
        public bool ShowSize { get; }
        // 是否显示时长
        public bool ShowLength { get; }

        int count = 0;

        public CountVideo(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            IsFront = arg.IsContain("-front");
            IsRemove = arg.IsContain("-remove");
            ShowSize = arg.IsContain("-size");
            ShowLength = arg.IsContain("-length");

        }

        public override void Execute() {
            Thread t = new Thread(StartProcess);
            t.Start();
        }

        private void StartProcess() {
            count = 0;
            var dir = new DirectoryInfo(FilePath);
            var files = Kit.GetAllFiles(null, dir, Kit.MEDIA_EXT);
            foreach (var f in files) {
                Process(f);
            }

            Flush($"成功改名：{count}/{files.Count}");

            End();
        }

        private void Process(FileInfo f) {
            var ffProbe = new NReco.VideoInfo.FFProbe();
            var videoInfo = ffProbe.GetMediaInfo(f.FullName);
            var stream = videoInfo.Streams[0];

            var pureName = Path.GetFileNameWithoutExtension(f.Name);
            var ext = Path.GetExtension(f.Name);
            pureName = RemoveTimeText(pureName);
            pureName = RemoveSizeText(pureName);
            var newName = string.Empty;
            var sizeStr = ShowSize ? $"[{stream.Width}x{stream.Height}]" : "";
            var lengthStr = ShowLength ? $"[{GetTimeString(videoInfo.Duration)}]" : "";

            if (IsRemove) {
                newName = $"{pureName}{ext}";
            } else {
                if (IsFront) {
                    newName = $"{sizeStr}{lengthStr}{pureName}{ext}";
                } else {
                    newName = $"{pureName}{sizeStr}{lengthStr}{ext}";
                }
            }            

            var newPath = Path.Combine(f.DirectoryName, newName);
            SetStatus(newName);

            if (File.Exists(newPath)) {
                Flush($"文件已经存在：{newPath}");
                return;
            }

            count++;
            File.Move(f.FullName, newPath);
        }


        public static string RemoveTimeText(string s) {            
            Regex r1 = new Regex(@"\[\d+s\]");
            Regex r2 = new Regex(@"\[\d+m\]");
            Regex r3 = new Regex(@"\[\d+m\d+s\]");
            Regex r4 = new Regex(@"\[\d+h\d+m\d+s\]");
            Regex r5 = new Regex(@"\[\d\d\.\d\d\.\d\d\]");
            string newName = s;
            if (r1.IsMatch(newName)) {
                newName = r1.Replace(newName, "");
            }
            if (r2.IsMatch(newName)) {
                newName = r2.Replace(newName, "");
            }
            if (r3.IsMatch(newName)) {
                newName = r3.Replace(newName, "");
            }
            if (r4.IsMatch(newName)) {
                newName = r4.Replace(newName, "");
            }
            if (r5.IsMatch(newName)) {
                newName = r5.Replace(newName, "");
            }
            return newName;
        }

        public static string RemoveSizeText(string s) {
            Regex r = new Regex(@"\[-?\d+x-?\d+\]");
            string newName = s;
            if (r.IsMatch(newName)) {
                newName = r.Replace(s, "");
            }
            return newName;
        }

        private string GetTimeString2(TimeSpan t) {
            return $"{t.Hours:D2}.{t.Minutes:D2}.{t.Seconds:D2}";
        }

        private string GetTimeString(TimeSpan t) {
            if (t.TotalMinutes >= 60) {
                return $"{t.Hours}h{t.Minutes}m";
            } else {
                if (t.TotalSeconds >= 60) {
                    if (t.TotalMinutes > 10) {
                        return $"{t.Minutes}m";                        
                    } else {
                        return $"{t.Minutes}m{t.Seconds}s";
                    }                    
                } else {
                    return $"{t.Seconds}s";
                }
            }
        }

        private void OnProcess(DirectoryInfo info) {
            try {
                count = Kit.Len(Kit.GetAllFiles(null, info, Kit.IMG_EXTS));
            } catch (IOException e) {
                Flush(e.Message);
                return;
            }

            var name = RemovePageText(info.Name.Trim());
            string newName;
            if (IsFront) {
                newName = string.Format("[{1}P]{0}", name, count);
            } else {
                newName = string.Format("{0}[{1}P]", name, count);
            }
            var newPath = Path.Combine(info.Parent.FullName, newName);
            if (Directory.Exists(newPath)) {
                return;
            }
            try {
                Directory.Move(info.FullName, newPath);
                SetStatus("成功改名：{0}", newPath);
            } catch (IOException e) {
                Flush(e.Message);
            }
        }


        public static string RemovePageText(string s) {
            Regex r = new Regex("\\[[0-9]+P\\]");
            string newName = s;
            if (r.IsMatch(s)) {
                newName = r.Replace(s, "");
            }
            return newName;
        }
    }
}
